#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

REPO_ROOT_PATH=$SCRIPTPATH/../
MAKE_FILE_PATH=$REPO_ROOT_PATH/Makefile
BIN_DIR=$SCRIPTPATH/../build/bin
mkdir -p $BIN_DIR

VERSION=$(make -s -f $MAKE_FILE_PATH version)
BASE_BIN_NAME=$(make -s -f $MAKE_FILE_PATH binary-name)
PLATFORMS=("linux/amd64")

USAGE=$(cat << 'EOM'
  Usage: build-binaries  [-p <platform pairs>]
  Builds static binaries for the platform pairs passed in

  Example: build-binaries -p "linux/amd64,linux/arm"
          Optional:
            -b          Base bin name [DEFAULT: output of "make binary-name"]
            -p          Platform pair list (os/architecture) [DEFAULT: linux/amd64]
            -v          VERSION: The application version of the docker image [DEFAULT: output of `make version`]
EOM
)

# Process our input arguments
while getopts "p:v:b:" opt; do
  case ${opt} in
    p ) # Platform Pairs
        IFS=',' read -ra PLATFORMS <<< "$OPTARG"
      ;;
    v ) # Image Version
        VERSION="$OPTARG"
      ;;
    b ) # Base bin name
        BASE_BIN_NAME="$OPTARG"
      ;;
    \? )
        echo "$USAGE" 1>&2
        exit
      ;;
  esac
done

for os_arch in "${PLATFORMS[@]}"; do
    os=$(echo $os_arch | cut -d'/' -f1)
    arch=$(echo $os_arch | cut -d'/' -f2)
    container_name="build-$BASE_BIN_NAME-$os-$arch"
    repo_name="bin-build"

    if [[ $os == "windows"* ]]; then
        bin_name="$BASE_BIN_NAME-$os-$arch.exe"
    else
        bin_name="$BASE_BIN_NAME-$os-$arch"
    fi

    docker container rm $container_name || :
    $SCRIPTPATH/build-docker-images -p $os_arch -v $VERSION -r $repo_name
    docker container create --rm --name $container_name "$repo_name:$VERSION-$os-$arch"
    docker container cp $container_name:/${BASE_BIN_NAME} $BIN_DIR/$bin_name

    if [[ $os == "windows"* ]]; then
      ## Create zip archive with binary taking into account windows .exe
      cp ${BIN_DIR}/${bin_name} ${BIN_DIR}/${BASE_BIN_NAME}.exe
      ## Can't reuse bin_name below because it includes .exe
      curr_dir=$(pwd)
      cd "${BIN_DIR}"
      zip -9 -q ${BASE_BIN_NAME}-$os-$arch.zip ${BASE_BIN_NAME}.exe
      cd "${curr_dir}"
      rm -f ${BIN_DIR}/${BASE_BIN_NAME}.exe
    else
      ## Create tar.gz archive with binary
      cp ${BIN_DIR}/${bin_name} ${BIN_DIR}/${BASE_BIN_NAME}
      tar -zcvf ${BIN_DIR}/${bin_name}.tar.gz -C ${BIN_DIR} ${BASE_BIN_NAME}
      rm -f ${BIN_DIR}/${BASE_BIN_NAME}
    fi
done
